<template>
	<view class="articleList">
		<cu-custom bgColor="bg-gradual-purple" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">文章管理</block>
		</cu-custom>
		<Loading :loadModal="loadModal" :hint="hint"></Loading>
		<!-- 搜索栏 -->
		<view class='box'>
			<form @submit='bindconfirm'>
				<view class="cu-bar search bg-white">
					<view class='search-form round'>
						<text class="cuIcon-search"></text>
						<input type="text" placeholder="搜索要操作的文章" v-model="defaultSearchValue" name="searchContent"
							confirm-type="search"></input>
					</view>
					<view class='action'>
						<button class='cu-btn bg-green shadow-blur round' form-type='submit'>搜索</button>
					</view>
				</view>
			</form>
			<scroll-view scroll-x class="bg-white nav solid-bottom">
				<view class="flex text-center">
					<view v-for="(item,idx) in navItems" :key="idx" :data-data="item" :data-id="item.index"
						class="cu-item flex-sub " :class="item.index==tabCur?'text-green cur':''" @tap='tabSelect'>
						{{item.name}}
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 文章列表 -->
		<view class="cu-card article no-card margin-top-self">
			<view v-for="(item,idx) in posts" :key="idx" :data-idx="idx" :id="item._id" @tap="bindPostDetail"
				class="cu-item shadow solids-bottom">
				<view class="title text-cut ">{{item.title}}</view>
				<view class="content">
					<image :src="item.defaultImageUrl" mode="aspectFill"></image>
					<view class="desc">
						<view class='text-content '>{{item.digest}}</view>
						<view>
							<view class="cu-tag light" :class="item.isShow==1?'bg-green':'bg-red'"
								:data-isshow="item.isShow" :data-postid="item._id" @click.stop='showModal'>
								{{item.isShow==1?"已展示":"隐藏中"}}
							</view>
							<view class="cu-tag light" :class="item.classify==0?'bg-red':'bg-green'"
								:data-classify="item.classify" :data-postid="item._id" @click.stop='showClassifyModal'>
								{{item.classify==0?"无专题":"有专题"}}
							</view>
							<view class="cu-tag light" :class="item.label.length==0?'bg-red':'bg-green'"
								:data-label="item.label" :data-postid="item._id" @click.stop='showLabelModal'>
								{{item.label.length==0?"无标签":"有标签"}}
							</view>
							<view class='cu-tag bg-red  light' :data-postid="item._id" @click.stop='showDeleteModal'>
								删除
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 数据不存在 -->
		<Nodata :noModal="nodata"></Nodata>

		<!-- 悬浮新增按钮 -->
		<view class="round-click" hover-class="none">
			<navigator :url='articlePath'>
				<text class="cuIcon-writefill"></text>
			</navigator>
		</view>

		<!-- 是否展示文章设置窗口 -->
		<view :class="isShowModel?'cu-modal show':'cu-modal'">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class='content'>{{showModelTitle}}</view>
					<view class='action' @tap='hideShowModal'>
						<text class='cuIcon-close text-red'></text>
					</view>
				</view>
				<view class='padding-xl'>{{showModelContent}}</view>
				<view class="cu-bar bg-white">
					<view class='action margin-0 flex-sub  solid-left' @tap='hideShowModal'>取消</view>
					<view class='action margin-0 flex-sub text-green solid-left' @tap='saveShowModal'>确定</view>
				</view>
			</view>
		</view>
		<!-- 展示标签选项 -->
		<view class="cu-modal bottom-modal" :class="isShowLabelModel?'show':''" @tap="hideLabelModal">
			<view class="cu-dialog" catchtap>
				<view class="cu-bar bg-white">
					<view class="action text-grey" @tap="hideLabelModal">取消</view>
					<view class="action text-green" @tap="saveLabelModal">提交</view>
				</view>
				<scroll-view class="VerticalNav nav" scroll-y scroll-with-animation :scroll-top="0"
					style="height:calc(100vh - 800rpx)">
					<view class="grid col-4 padding-sm">
						<view class="padding-xs" v-for="(item,idx) in otherLabels" :key="idx">
							<button class="cu-btn orange block" :class="item.checked?'bg-orange':'line-orange'"
								@tap="chooseLabelCheckbox" :data-checked="item.checked" :data-value="item.name">
								{{item.name}}
							</button>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 展示专题选项 -->
		<view class="cu-modal bottom-modal" :class="isShowClassifyModel?'show':''" @tap="hideClassifyModal">
			<view class="cu-dialog " catchtap>
				<view class="cu-bar bg-white ">
					<view class="action text-grey" @tap="hideClassifyModal">取消</view>
					<view class="action text-green" @tap="saveClassifyModal">提交</view>
				</view>
				<scroll-view class="VerticalNav nav" scroll-y scroll-with-animation :scroll-top="0"
					style="height:calc(100vh - 800rpx)">
					<view class="cu-dialog">
						<radio-group class="block" @change="radioClassifyChange">
							<view class="cu-list menu text-left">
								<view class="cu-item" v-for="(item,idx) in classifyList" :key="idx" :id="item._id">
									<label class="flex justify-between align-center flex-sub">
										<view class="flex-sub">{{item.name}}</view>
										<radio :checked="item.checked" :value="item.name" class="round"></radio>
									</label>
								</view>
							</view>
						</radio-group>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 删除文章设置窗口 -->
		<view :class="isShowDeleteModel?'cu-modal show':'cu-modal'">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class='content'>删除文章</view>
					<view class='action' @tap='hideShowDeleteModal'>
						<text class='cuIcon-close text-red'></text>
					</view>
				</view>
				<view class='padding-xl'>是否确认删除文章，删除后将无法恢复</view>
				<view class="cu-bar bg-white">
					<view class='action margin-0 flex-sub  solid-left' @tap='hideShowDeleteModal'>取消</view>
					<view class='action margin-0 flex-sub text-green solid-left' @tap='deleteShowModal'>
						确定
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Loading from '../../components/loading.vue';
	import Nodata from '../../components/nodata.vue';
	import util from '../../utils/util.js';
	import api from '../../utils/api.js';
	export default {
		components: {
			Loading,
			Nodata
		},
		data() {
			return {
				imgUrl: getApp().globalData.imgUrl,
				navItems: [{
					name: '已展示',
					index: 1
				}, {
					name: '未展示',
					index: 2
				}, {
					name: '有专题',
					index: 3
				}, {
					name: '无专题',
					index: 4
				}, {
					name: '有标签',
					index: 5
				}, {
					name: '无标签',
					index: 6
				}],
				tabCur: 1,
				scrollLeft: 0,
				filter: {
					isShow: 1
				},
				posts: [],
				page: 1,
				nodata: false,
				loadModal: false, //加载
				hint: '加载中...',
				articlePath: "../admin/article",
				isShowModel: false,
				isShowDeleteModel: false,
				showModelTitle: "文章是否显示",
				showModelContent: "",
				showCurPostId: "", //当前操作的文章id
				showCurStatus: 0,
				selectedLabels: [],
				otherLabels: [],
				isShowLabelModel: false,
				isShowClassifyModel: false,
				classifyList: [],
				showCurClassify: "",
				defaultSearchValue: ""
			}
		},
		onLoad: async function(options) {},
		onShow: async function() {
			this.page = 1;
			this.hint = '加载中...';
			let filter = {
				isShow: 1
			}
			await this.getPostsList(filter)
		},
		methods: {
			/**
			 * tab切换
			 * @param {} e 
			 */
			tabSelect: async function(e) {
				let that = this;
				let tabCur = e.currentTarget.dataset.id;
				let filter = {};
				that.tabCur = e.currentTarget.dataset.id;
				that.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
				that.defaultSearchValue = "";
				that.hint = '加载中...';
				that.page = 1;
				switch (tabCur) {
					case 1: {
						filter.isShow = 1;
						break
					}
					case 2: {
						filter.isShow = 0;
						break
					}
					case 3: {
						filter.hasClassify = 1;
						break
					}
					case 4: {
						filter.hasClassify = 2;
						break;
					}
					case 5: {
						filter.hasLabel = 1;
						break;
					}
					case 6: {
						filter.hasLabel = 2;
						break
					}
				}
				
				that.filter = filter;
				await that.getPostsList(filter)
			},
			/**
			 * 搜索功能
			 * @param {} e 
			 */
			bindconfirm: async function(e) {
				let that = this;
				console.log('e.detail.value', e.detail.value.searchContent)
				that.page = 1;
				// that.filter.title = e.detail.value.searchContent;
				
				that.hint = '加载中...';
				await that.getPostsList(that.filter);
			},
			/**
			 * 获取文章列表
			 */
			getPostsList: async function(filter) {
				let that=this;
				let page = that.page;
				filter.title=that.defaultSearchValue;
				that.loadModal = true;
				let result = await api.getNewPostsList(page, filter);
				that.loadModal = false;
				that.posts = that.page == 1 ? result.data : [...that.posts, ...result.data];
				that.nodata = result.data.length === 0 && page == 1 ? true : false;
				if (result.data.length == 0) {
				  uni.showToast({
				    title: '没有更多数据了！',
				    icon: 'none',
				    duration: 2000
				  })
				}
				uni.hideNavigationBarLoading();
				uni.hideLoading();
				uni.stopPullDownRefresh();
			},
			/**
			 * 点击文章明细
			 */
			bindPostDetail: function(e) {
				let blogId = e.currentTarget.id;
				uni.navigateTo({
					url: '../admin/article?id=' + blogId
				})
			},
			/**
			 * 显示设置文章窗口
			 * @param {*} e 
			 */
			showModal: function(e) {
				let that = this;
				let isShow = e.currentTarget.dataset.isshow;
				let postId = e.currentTarget.dataset.postid;

				that.isShowModel = true;
				that.showModelContent = isShow == 1 ? "是否确认将文章设置为[前端不展示]" : "是否确认将文章设置为[前端展示]";
				that.showCurPostId = postId;
				that.showCurStatus = isShow;
			},
			/**
			 * 显示设置专题标签窗口
			 * @param {*} e 
			 */
			showClassifyModal: async function(e) {
				uni.showLoading({
					title: '专题加载中...',
				});

				let that = this;
				let postId = e.currentTarget.dataset.postid;
				let curClassify = e.currentTarget.dataset.classify == 0 ? "" : e.currentTarget.dataset.classify;
				let classifyList = await api.getClassifyList();
				let classify = [];
				if (curClassify != "") {
					classify.push({
						name: curClassify,
						checked: true
					})
				}

				for (var index in classifyList.result.data) {

					if (curClassify == classifyList.result.data[index].value.classifyName) {
						continue;
					}

					classify.push({
						name: classifyList.result.data[index].value.classifyName,
						checked: false
					});
				}

				that.isShowClassifyModel = true;
				that.classifyList = classify;
				that.showCurClassify = curClassify;
				that.showCurPostId = postId;
				uni.hideLoading()
			},
			/**
			 * 显示设置文章标签窗口
			 * @param {*} e 
			 */
			showLabelModal: async function(e) {
				uni.showLoading({
					title: '标签加载中...',
				})

				let that = this
				let postId = e.currentTarget.dataset.postid
				let label = e.currentTarget.dataset.label
				let labelList = await api.getLabelList()
				let otherLabels = []
				if (label.length > 0) {
					for (var i = 0; i < label.length; i++) {
						otherLabels.push({
							name: label[i],
							checked: true
						})
					}
				}

				for (var index in labelList.result.data) {
					let labelRes = otherLabels.filter((a) => labelList.result.data[index].value == a.name)
					if (labelRes.length > 0) {
						continue;
					}

					otherLabels.push({
						name: labelList.result.data[index].value,
						checked: false
					})
				}

				that.isShowLabelModel = true;
				that.selectedLabels = label;
				that.otherLabels = otherLabels;
				that.showCurPostId = postId;

				uni.hideLoading()

			},
			showDeleteModal: function(e) {
				this.isShowDeleteModel = true;
				this.showCurPostId = e.currentTarget.dataset.postid;
			},
			/**
			 * 设置隐藏
			 * @param {*} e 
			 */
			hideShowModal: function(e) {
				this.isShowModel = false;
			},
			/**
			 * 设置隐藏
			 * @param {*} e 
			 */
			hideLabelModal: function(e) {
				this.isShowLabelModel = false;
			},
			/**
			 * 设置隐藏
			 * @param {*} e 
			 */
			hideClassifyModal: function(e) {
				this.isShowClassifyModel = false;
			},
			hideShowDeleteModal: function(e) {
				this.isShowDeleteModel = false;
			},

			/**
			 * 前端是否展示
			 * @param {*} e 
			 */
			saveShowModal: async function(e) {
				uni.showLoading({
					title: '加载中...',
				});
				try {
					let that = this;
					let updateShow = that.showCurStatus == 0 ? 1 : 0
					let res = await api.updatePostsShowStatus(that.showCurPostId, updateShow)
					console.info(res);
					if (res.result) {
						that.isShowModel = false;
						that.showModelContent = "";
						that.showCurPostId = "";
						that.showCurStatus = -1;

						that.page = 1;
						await that.getPostsList(that.filter);

						uni.showToast({
							title: '设置成功',
							icon: 'success',
							duration: 1500
						})
					} else {
						uni.showToast({
							title: '操作发生未知异常',
							duration: 1500
						})
					}
				} catch (err) {
					uni.showToast({
						title: '程序有一点点小异常，操作失败啦',
						icon: 'none',
						duration: 1500
					})
					console.info(err)
				} finally {
					uni.hideLoading()
				}
			},
			/**
			 * 保存专题信息
			 * @param {*} e 
			 */
			saveClassifyModal: async function(e) {
				uni.showLoading({
					title: '保存中...',
				})

				try {
					let that = this
					let postId = that.showCurPostId;
					console.info(postId)
					console.info(that.showCurClassify)
					let newPost = {
						classify: that.showCurClassify
					}

					let res = await api.upsertPosts(postId === undefined ? "" : postId, newPost);
					if (res.result) {
						that.isShowClassifyModel = false;
						that.showCurClassify = "";
						that.classifyList = [];
						that.showCurPostId = "";

						that.page = 1;
						await that.getPostsList(that.filter);

						uni.showToast({
							title: '设置成功',
							icon: 'success',
							duration: 1500
						})
					} else {
						uni.showToast({
							title: '操作发生未知异常',
							duration: 1500
						})
					}
				} catch (err) {
					uni.showToast({
						title: '程序有一点点小异常，操作失败啦',
						icon: 'none',
						duration: 1500
					})
					console.info(err)
				} finally {
					wx.hideLoading()
				}
			},
			/**
			 * 保存标签信息
			 * @param {*} e 
			 */
			saveLabelModal: async function(e) {
				uni.showLoading({
					title: '保存中...',
				})

				try {
					let that = this;
					let postId = that.showCurPostId;
					let newPost = {
						label: that.selectedLabels
					}

					let res = await api.upsertPosts(postId === undefined ? "" : postId, newPost);
					if (res.result) {
						that.isShowLabelModel = false;
						that.selectedLabels = [];
						that.otherLabels = [];
						that.showCurPostId = "";
						that.page = 1;
						await that.getPostsList(that.filter);

						uni.showToast({
							title: '设置成功',
							icon: 'success',
							duration: 1500
						})
					} else {
						uni.showToast({
							title: '操作发生未知异常',
							duration: 1500
						})
					}
				} catch (err) {
					uni.showToast({
						title: '程序有一点点小异常，操作失败啦',
						icon: 'none',
						duration: 1500
					})
					console.info(err)
				} finally {
					uni.hideLoading()
				}

			},
			/**
			 * 删除文章
			 * @param {*} e 
			 */
			deleteShowModal: async function(e) {
				uni.showLoading({
					title: '加载中...',
				})
				try {
					let that = this;
					let res = await api.deletePostById(that.showCurPostId)
					console.info(res)
					if (res.result) {
						that.isShowDeleteModel = false;
						that.showCurPostId = "";
						that.page = 1;
						await that.getPostsList(that.filter);

						uni.showToast({
							title: '删除成功',
							icon: 'success',
							duration: 1500
						})
					} else {
						uni.showToast({
							title: '操作发生未知异常',
							duration: 1500
						})
					}
				} catch (err) {
					uni.showToast({
						title: '程序有一点点小异常，操作失败啦',
						icon: 'none',
						duration: 1500
					})
					console.info(err)
				} finally {
					uni.hideLoading()
				}
			},
			/**
			 * 选择标签
			 * @param {} e 
			 */
			chooseLabelCheckbox(e) {
				let that = this;
				let selectedLabels = that.selectedLabels;
				let otherLabels = that.otherLabels;
				let name = e.currentTarget.dataset.value;
				let checked = e.currentTarget.dataset.checked;

				for (let i = 0; i < otherLabels.length; i++) {
					if (otherLabels[i].name == name) {
						otherLabels[i].checked = !otherLabels[i].checked;
						break
					}
				}
				if (checked) {
					var index = selectedLabels.indexOf(name);
					if (index > -1) {
						selectedLabels.splice(index, 1);
					}
				} else {
					selectedLabels.push(name)
				}

				that.otherLabels = otherLabels;
				that.selectedLabels = selectedLabels;
			},

			/**
			 * 专题选择变化事件
			 * @param {*} e 
			 */
			radioClassifyChange: function(e) {
				let curClassify = e.detail.value;
				console.info(curClassify)
				this.showCurClassify = curClassify;
			},
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: async function() { //下拉刷新
			this.page = 1;
			this.hint = '刷新中...';
			await this.getPostsList(this.filter);
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: async function() { //上拉加载
			this.page = this.page + 1;
			this.hint = '加载中...';
			await this.getPostsList(this.filter);
		}
	}
</script>

<style>
	.round-click {
		height: 120rpx;
		width: 120rpx;
		background-color: #d92a2a;
		border-radius: 100%;
		position: fixed;
		bottom: 100rpx;
		right: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9;
	}

	.round-click navigator {
		font-size: 50rpx;
		max-width: 80rpx;
		color: #fff;
		text-align: center;
	}
</style>
